import { showSuccess, showWarning } from '@/components/antd-comp/message/useNotification'
import { getPublished_list, saveAssistanttApi } from '@/controllers/API/assistant'
import { toolsSaveRecord } from '@/controllers/API/tools'
import { useAssistantStore } from '@/store/assistantStore'
// import { useBuriedStore } from '@/store/buriedStore'
import { useChatStore } from '@/components/Chat/chatStore'
import { userContext } from '@/contexts/userContext'
import { Func } from '@/permissions/constants'
import { useFuncsStore } from '@/store/funcStore'
import { useBuriedEvent } from '@/util/buried'
import type { GetRef, TourProps } from 'antd'
import { Button, Tour } from 'antd'
import { throttle } from 'lodash'
import { useContext, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useParams } from 'react-router-dom'
import { useNavigate } from 'react-router-dom'
import DataBoard from './components/DataBoard'
import Header from './components/Header'
import Prompt from './components/Prompt'
import Setting from './components/Setting'
import TestChat from './components/TestChat'
import TourSvg_def from './components/TourSvg'
import './css/styles.css'
export default function ApplicationEditPage() {
  /**
   * 功能权限限制
   */
  const { hasFuncPermission } = useFuncsStore()
  // ------埋点------
  const { applicationBuriedEvent } = useBuriedEvent()

  const { user } = useContext(userContext)

  // 统计停留时长
  useEffect(() => {
    let startTime
    let endTime

    const handleStart = () => {
      startTime = Date.now()
    }

    const handleEnd = () => {
      endTime = Date.now()
      applicationBuriedEvent({
        page: '智能体配置页面',
        event_type: '停留时长',
        event_name: '智能体配置页面-停留时长',
        data_id: assistantId,
        dwell_timed: endTime - startTime
      })
    }

    // 页面加载时开始计时
    handleStart()

    // 页面销毁时统计停留时间
    return () => {
      handleEnd()
    }
  }, [])

  // 编辑和数据看板切换
  const [activeType, setActiveType] = useState('edit')

  const { t } = useTranslation()
  const { id: assistantId } = useParams<{ id: string }>()
  const navigate = useNavigate()
  // assistant data
  const {
    assistantState,
    dispatchAssistant,
    changed,
    toolList,
    loadAssistantState,
    saveAfter,
    destroy,
    dispatchToolList
  } = useAssistantStore()
  const { running, startNewRound, updateGuideMessage, setShowGuideQuestion, updateLimitInfo } = useChatStore()

  useEffect(() => {
    loadAssistantState(assistantId).then(res => {
      setShowGuideQuestion(true)
      setGuideQuestion(res.guide_question?.filter(item => item) || [])
      res.guide_word && updateGuideMessage(res.guide_word, true)
    })
  }, [])

  useEffect(() => {
    updateLimitInfo({
      remember_mode: assistantState.remember_mode, // 0 最后轮次，1 最后分钟数
      remember_last_num: assistantState.remember_last_num,
      remember_last_minute: assistantState.remember_last_minute
    })
  }, [assistantState.remember_mode, assistantState.remember_last_num, assistantState.remember_last_minute])

  useEffect(() => {
    // 只有用户拥有自定义插件获取权限才需要绑定智能体和新增的插件id
    if (hasFuncPermission([Func.tools.query], false)) {
      getPublished_list(null, true).then(res => {
        const list = res.list ? res.list : []
        const customTools = []
        list.forEach(item => {
          customTools.push(item)
          if (item.children && item.children.length) {
            item.children.forEach(child => {
              customTools.push({ ...child, tool_id: item.tool_id })
            })
          }
        })
        dispatchToolList('setting', customTools)
      })
    }

    /* 引导指南 */
    // const saved = localStorage.getItem('applicationEditCreate')
    // if (saved && saved === '1') {
    //   setOpenTour(true)
    //   localStorage.setItem('applicationEditCreate', '')
    // }
  }, [])

  // 展示的引导词独立存储
  const [guideQuestion, setGuideQuestion] = useState([])

  const [needRecord, setNeedRecord] = useState(changed)
  useEffect(() => {
    setNeedRecord(changed)
  }, [changed])

  const handleStartChat = async params => {
    if (!handleCheck()) return
    if (!needRecord) return
    setNeedRecord(false)
    await handleSave(true, 'inputPostion')
    saveAfterFun()
  }
  const handleSave_startChat = async (showMessage = false, type?: any, buriedInfo = null) => {
    if (!handleCheck()) return
    // if (!needRecord) return
    setNeedRecord(false)
    await handleSave(showMessage, type, buriedInfo)
    saveAfterFun()
  }

  // input前端保存操作：1s时间间隔内重复点击只执行第一次
  const recordBeforeInput = throttle(handleStartChat, 1000, {
    leading: true,
    trailing: false
  })

  function saveAfterFun() {
    saveAfter()
    startNewRound(true)
    setGuideQuestion(assistantState.guide_question.filter(item => item))
    assistantState.guide_word && updateGuideMessage(assistantState.guide_word, true)
  }
  // 保存助手详细信息
  const handleSave = async (showMessage = false, type?: any, buriedInfo = null) => {
    if (!hasFuncPermission([Func.assistant.edit])) {
      return
    }
    if (!handleCheck()) return
    try {
      await toolsSaveRecord({
        assistant_id: assistantState.id,
        assistant_name: assistantState.name,
        // tool_ids: getToolUuidList(assistantState.tool_list)
        tool_ids: assistantState.tool_list.map(item => item.tool_id)
      })
    } catch {
      return
    }
    if (!hasFuncPermission([Func.assistant.configEdit])) {
      return
    }
    await saveAssistanttApi({
      ...assistantState,
      flow_list: assistantState.flow_list.map(item => item.id) as any,
      tool_list: assistantState.tool_list.map(item => item.id),
      knowledge_list: assistantState.knowledge_list.map(item => item.id),
      guide_question: assistantState.guide_question.filter(item => item),
      guide_word: assistantState.guide_word
        ? assistantState.guide_word
        : '你好，我是智能助手。我会尽我所能帮助你，请随时告诉我你的问题。',
      query_template:
        assistantState.category_code == '100' || assistantState.category_code == '101'
          ? assistantState.query_template
          : null
    })
      .then(res => {
        const resultStatus = '成功'
        showMessage && showSuccess(t('prompt'), t('skills.saveSuccessful'))
        setTimeout(() => {
          const submitBuriedInfo: any = {}
          if (buriedInfo) {
            submitBuriedInfo.event_name = buriedInfo.event_name
            submitBuriedInfo.page = buriedInfo.page
            const detail = {
              类型: assistantState.category_code,
              结果: resultStatus
            }
            if (buriedInfo.event_name === '【保存】按钮') {
              detail['温度数'] = assistantState.temperature
              detail['选择模型'] = assistantState.model_name
              detail['回复风格类型'] = assistantState.reply_style
              detail['知识库id'] = assistantState.knowledge_list.map(item => item.id)
              detail['插件id'] = assistantState.tool_list.map(item => item.id)
            }

            applicationBuriedEvent({
              ...submitBuriedInfo,
              data_id: assistantState.id,
              detail: JSON.stringify(detail)
            })
          }
        })
        if (!res) return
        // 操作续连
        if (!type) {
          saveAfterFun()
        }
      })
      .finally(() => {
        dispatchAssistant('setting', { role_save_judgment: '' })
      })
  }

  const getToolUuidList = usedList => {
    if (!usedList || usedList.length === 0 || !toolList || toolList.length === 0) {
      return []
    }
    const usedMap = new Map(usedList.map(item => [`${item.id}-${item.name}`, true]))
    return toolList.filter(item => usedMap.has(`${item.id}-${item.name}`)).map(item => item.tool_id)
  }

  /* 上线loading */
  const [topLineLoading, setTopLineLoading] = useState(false)
  // 上线助手
  const handleOnline = async () => {
    setTopLineLoading(true)
    try {
      if (!hasFuncPermission([Func.assistant.online]) || !handleCheck()) {
        return
      }
      await handleSave()
      navigate('/applicationEdit/topLine/' + assistantState.id)
    } catch (error) {
      console.error('Error in handleOnline:', error)
    } finally {
      setTopLineLoading(false)
    }
  }

  // 校验助手数据
  const handleCheck = () => {
    const errors = []
    if (!assistantState.prompt && !assistantState.role_save_judgment) {
      errors.push('角色设定不能为空')
    }
    const list = assistantState.guide_question.filter(item => item)
    if (list.length > 10) {
      errors.push('引导问题上限10个')
    }
    if (assistantState.guide_question.some(que => que.length > 50)) {
      errors.push(t('skills.guideQuestions50'))
    }
    if (assistantState.guide_word.length > 1000) {
      errors.push(t('skills.promptWords1000'))
    }

    if (errors.length) {
      showWarning(t('prompt'), errors)
      return false
    }
    return true
  }

  // 销毁
  useEffect(() => {
    return destroy
  }, [])

  /* 引导 */
  const buttonRefs = Array.from({ length: 5 }, () => useRef<GetRef<typeof Button>>(null))
  const [openTour, setOpenTour] = useState<boolean>(false)
  const stepsData = [
    {
      title: '请在此设定描述智能体的角色，例如身份、完成任务的具体方法和步骤等。',
      targetIndex: 0,
      placement: 'right',
      nextButtonProps: {
        className: 'custom_button custom_button_all',
        children: '下一步'
      }
    },
    {
      title: '可选择使用的模型、回复风格，及用户在会话页面能够看到的开场白引导。',
      targetIndex: 1,
      prevButtonProps: {
        className: 'custom_button_next custom_button_all',
        children: '上一步'
      },
      nextButtonProps: {
        className: 'custom_button custom_button_all',
        children: '下一步'
      }
    },
    {
      title: '可为智能体添加更多知识、插件等，拓展智能体的回答能力。',
      targetIndex: 2,
      prevButtonProps: {
        className: 'custom_button_next custom_button_all',
        children: '上一步'
      },
      nextButtonProps: {
        className: 'custom_button custom_button_all',
        children: '下一步'
      }
    },
    {
      title: '此处可查看智能体设置的效果，进行预览调试。',
      targetIndex: 3,
      placement: 'left',
      prevButtonProps: {
        className: 'custom_button_next custom_button_all',
        children: '上一步'
      },
      nextButtonProps: {
        className: 'custom_button custom_button_all',
        children: '下一步'
      }
    },
    {
      title: '可选择不同平台上线智能体并查看。',
      targetIndex: 4,
      placement: 'bottom',
      cover: (
        // <img
        //   alt="tour.png"
        //   src="https://user-images.githubusercontent.com/5378891/197385811-55df8480-7ff4-44bd-9d43-a7dade598d70.png"
        // />
        <TourSvg_def></TourSvg_def>
      ),
      prevButtonProps: {
        className: 'custom_button_next custom_button_all',
        children: '上一步'
      },
      nextButtonProps: {
        className: 'custom_button custom_button_all',
        children: '确定'
      }
    }
  ]
  const steps: TourProps['steps'] = stepsData.map(step => ({
    ...step,
    target: () => buttonRefs[step.targetIndex].current!
  })) as any
  /* 样式 */
  const RADIUS = 12
  const OFFSET_GAP = { offset: [5] as [number] }

  return (
    <div className="bg-[#F4F5F8]">
      <Header
        onSave={({ buriedInfo }) => {
          handleSave_startChat(
            true,
            null,
            buriedInfo || {
              page: '智能体配置页面',
              event_name: '【保存】按钮'
            }
          )
        }}
        onLine={handleOnline}
        activeType={activeType}
        setActiveType={setActiveType}
        topLineLoading={topLineLoading}
        propsRef={buttonRefs[4]}
      ></Header>
      <div className="flex h-[calc(100vh-68px)]">
        {activeType === 'edit' ? (
          <>
            <div className="w-[60%]">
              <div className="applicationEditPage_headStting_title h-[48px]">{t('application.appliPageSetting')}</div>
              <div className="flex h-[calc(100vh-117px)]">
                <Prompt propsRef={buttonRefs[0]}></Prompt>
                <Setting propsRef2={buttonRefs[1]} propsRef={buttonRefs[2]}></Setting>
              </div>
            </div>
            <div className="relative h-full w-[40%] bg-[#fff]">
              <TestChat
                propsRef={buttonRefs[3]}
                guideQuestion={guideQuestion}
                assistantId={assistantId}
                useName={user.user_name}
                modelName={assistantState.model_name}
              ></TestChat>
              {/* 变更触发保存的蒙版按钮 */}
              {changed && !running && <div className="absolute bottom-0 h-72 w-full" onClick={recordBeforeInput}></div>}
            </div>
          </>
        ) : (
          <>
            <DataBoard id={assistantId}></DataBoard>
          </>
        )}
      </div>
      <Tour
        open={openTour}
        onClose={() => setOpenTour(false)}
        steps={steps}
        disabledInteraction={true}
        gap={{ offsetGap: OFFSET_GAP, radius: RADIUS } as any}
        indicatorsRender={(current, total) => (
          <span>
            {current + 1} / {total}
          </span>
        )}
      />
    </div>
  )
}
